package com.robusta.spreadsheet.model;

import com.robusta.spreadsheet.model.exception.WorkbookException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;

import java.io.*;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.robusta.spreadsheet.model.impl.RobustaWorkbookFactory.newWorkbook;

/**
 * Utilities to build Robusta Workbook objects (wrapper on Apache POI)
 * from a excel work book content. The content is specified as a file
 * or Input stream.
 * A workbook template is used to describe the workbook content.
 * @author sudhir ravindramohan sudhirbits@gmail.com
 * @since 1.0
 * @see WorkbookTemplate
 * @see WorksheetTemplate
 */
public class WorkbookFactory {
    public static Workbook create(File file, WorkbookTemplate template) throws WorkbookException {
        checkArgument(file != null, "File argument is invalid. Expecting a locatable and readable file with workbook content.");
        checkArgument(template != null, "Template is invalid, Expecting a not null template that can describe the workbook content.");
        try {
            return create(new FileInputStream(file), template);
        } catch (FileNotFoundException e) {
            throw new WorkbookException(String.format("File does not exist: %s", file), e);
        }
    }

    public static Workbook create(InputStream inputStream, WorkbookTemplate template) throws WorkbookException {
        org.apache.poi.ss.usermodel.Workbook workbook;
        try {
            workbook = org.apache.poi.ss.usermodel.WorkbookFactory.create(inputStream);
        } catch (IOException e) {
            throw new WorkbookException("File could not be read as a excel workbook", e);
        } catch (InvalidFormatException e) {
            throw new WorkbookException("Reading the excel workbook with apache POI caused a format error", e);
        }
        checkState(workbook != null, "Creation of workbook from apache POI returned an invalid model");
        return newWorkbook(workbook, template);
    }
}
